package com.spn.blog.login.service.impl;

import com.spn.blog.common.dao.pojo.SysUser;
import com.spn.blog.common.vo.Result;
import com.spn.blog.common.vo.params.TpuserBindParam;
import com.spn.blog.login.params.PrividerToken;
import com.spn.blog.login.privider.AccessPrivider;
import com.spn.blog.login.service.SysUserTpusersService;
import com.spn.blog.service.login.OtherLogin;
import com.spn.blog.service.login.SysUserService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;

@DubboService
public class OtherLoginImpl implements OtherLogin {
    @Autowired
    private PrividerToken prividerToken;
    @Autowired
    private AccessPrivider accessPrivider;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTpusersService sysUserTpusersService;

    @Override
    public Result userbind(TpuserBindParam tpuserBindParam) {
        return sysUserTpusersService.userbind(tpuserBindParam);
    }

    @Override
    public Result secondlogin(TpuserBindParam tpuserBindParam) {
        return sysUserTpusersService.secondlogin(tpuserBindParam);
    }

    @Value("${callback.clientId}")
    private String clientId;
    @Value("${callback.clientSecret}")
    private String clientSecret;
    @Value("${callback.ip}")
    private String callbackIp;


    @Override
    public String callback(String code, String state) {
        prividerToken.setClient_id(clientId);
        prividerToken.setClient_Secret(clientSecret);
        prividerToken.setCode(code);
        prividerToken.setState(state);
        prividerToken.setRedirect_uri("https://" + callbackIp + "/api/callback");
        String token = accessPrivider.getToken(prividerToken);
//        //通过token获取用户id，判断用户id是否和user表的用户有关联
        SysUser tpUser = accessPrivider.getSysUser(token);
        SysUser sysUser = sysUserService.findUserBytpUserId(tpUser.getId());
        if (sysUser == null) {
            //说明没有关联，返回页面地址进行关联
            return "redirect:http://" + callbackIp + ":80/#/userbind?token=" + token;
        }
        //有关联就返回缓冲页，在缓冲进行初始化登录
        return "redirect:http://" + callbackIp + ":80/#/loginloading?token=" + token;
    }
}
